package com.chushouya.order.service.api.impl;

import com.general.framework.core.lang.*;
import com.chushouya.common.support.Contexts;
import com.general.framework.core.exception.Ex;
import com.chushouya.order.constants.OrderActionEnum;
import com.chushouya.order.constants.OrderStatusEnum;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderProductEntity;
import com.chushouya.order.dao.repository.OrderProductRepository;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dto.admin.order.OrderQuery;
import com.chushouya.order.dto.api.clerk.action.ClerkSubmitQualityAction;
import com.chushouya.order.dto.api.quality.QualityItemApiDTO;
import com.chushouya.order.service.api.ClerkOrderQualityApiService;
import com.chushouya.order.service.common.OrderLogService;
import com.chushouya.product.dto.api.evaluate.EvaluateListApiDTO;
import com.chushouya.product.dto.api.evaluate.EvaluateResultItemApiDTO;
import com.chushouya.product.dto.api.evaluate.EvaluateValueApiDTO;
import com.chushouya.product.service.api.EvaluateApiService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ClerkOrderQualityApiServiceImpl implements ClerkOrderQualityApiService {

    @Resource
    private EvaluateApiService evaluateApiService;

    @Resource
    private OrderLogService orderLogService;

    @Resource
    private OrderProductRepository orderProductRepository;

    @Resource
    private OrderRepository orderRepository;


    private OrderEntity getOrder(Long orderId,Long clerkId) {
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setOrderId(orderId);
//        orderQuery.setClerkId(clerkId);
        OrderEntity orderEntity  = orderRepository.selectOne(orderQuery);
        if(Objects.isNull(orderEntity )){
            throw Ex.business("无法访问订单信息");
        }
        return orderEntity;
    }

    /**
     * 获取订单产品信息
     * @param orderId
     * @return
     */
    private OrderProductEntity getOrderProduct(Long orderId) {
        OrderProductEntity orderProductEntity = orderProductRepository.selectByOrderId(orderId);
        if(Objects.isNull(orderProductEntity)){
            throw Ex.business("订单产品不存在");
        }
        return orderProductEntity;
    }

    @Override
    public List<QualityItemApiDTO> orderQualityItem(Long orderId) {
        // 1. 获取基础数据
        final Long clerkId = Contexts.getUserContext().getClerkId();
        OrderEntity orderEntity = getOrder(orderId, clerkId);
        OrderProductEntity orderProductEntity = getOrderProduct(orderId);
        final Long productId = orderProductEntity.getProductId();
        
        // 2. 解析评估和质检数据
        List<EvaluateResultItemApiDTO> evaluateResultItemList = parseEvaluateItems(orderProductEntity.getEvaluateItem());
        List<EvaluateResultItemApiDTO> qualityResultItemList = parseEvaluateItems(orderProductEntity.getQualityItem());
        
        // 3. 获取商品评估列表并转换为质检项
        List<EvaluateListApiDTO> evaluateList = evaluateApiService.productEvaluateList(productId);
        List<QualityItemApiDTO> qualityItemList = Beans.copyList(evaluateList, QualityItemApiDTO.class);
        
        // 4. 初始化质检项的值列表
        initializeQualityItemValues(qualityItemList);
        
        // 5. 设置用户评估值和质检值
        populateUserValues(qualityItemList, evaluateResultItemList);
        populateQualityValues(qualityItemList, qualityResultItemList);
        
        return qualityItemList;
    }

    @Override
    public void qualityOrder(OrderEntity orderEntity, ClerkSubmitQualityAction qualitySubmit) {
        OrderEntity update = new OrderEntity();
        update.setOrderId(orderEntity.getOrderId());
        update.setQualityPrice(qualitySubmit.getQualityPrice());
        update.setCompletePrice(qualitySubmit.getQualityPrice());
        update.setQualityTime(Dates.getTimeNow());
        update.setOrderStatus(OrderStatusEnum.WAIT_PAY.value());
        orderRepository.updateByPrimaryKeySelective(update);
        // 更新订单产品的质检项
        OrderProductEntity orderProductEntity = getOrderProduct(orderEntity.getOrderId());
        OrderProductEntity orderProductUpdate = new OrderProductEntity();
        orderProductUpdate.setOrderId(orderEntity.getOrderId());
        orderProductUpdate.setQualityItem(Jsons.toJsonString(qualitySubmit.getQualityOption()));
        orderProductUpdate.setQualityPrice(qualitySubmit.getQualityPrice());
        orderProductUpdate.setOrderProductId(orderProductEntity.getOrderProductId());
        orderProductRepository.updateByPrimaryKeySelective(orderProductUpdate);

        //插入订单操作记录
        final String msg = Strings.format("业务员提交质检，质检价格：{}元", qualitySubmit.getQualityPrice());
        orderLogService.addOrderActionLog(orderEntity.getOrderId(), OrderActionEnum.QUALITY_ORDER.value(), msg);

    }

    /**
     * 解析评估项数据
     */
    private List<EvaluateResultItemApiDTO> parseEvaluateItems(String evaluateItemJson) {
        if (Objects.isNull(evaluateItemJson)) {
            return Lists.newArrayList();
        }
        return Jsons.parseArray(evaluateItemJson, EvaluateResultItemApiDTO.class);
    }
    
    /**
     * 初始化质检项的值列表，避免空指针异常
     */
    private void initializeQualityItemValues(List<QualityItemApiDTO> qualityItemList) {
        for (QualityItemApiDTO qualityItem : qualityItemList) {
            if (Objects.isNull(qualityItem.getUserValues())) {
                qualityItem.setUserValues(new ArrayList<>());
            }
            if (Objects.isNull(qualityItem.getQualityValues())) {
                qualityItem.setQualityValues(new ArrayList<>());
            }
        }
    }
    
    /**
     * 填充用户评估值
     */
    private void populateUserValues(List<QualityItemApiDTO> qualityItemList, 
                                   List<EvaluateResultItemApiDTO> evaluateResultItemList) {
        if (Lists.isEmpty(evaluateResultItemList)) {
            return;
        }
        
        for (QualityItemApiDTO qualityItem : qualityItemList) {
            for (EvaluateResultItemApiDTO evaluateResultItem : evaluateResultItemList) {
                if (Objects.equals(qualityItem.getAttrName(), evaluateResultItem.getAttrName())) {
                    EvaluateValueApiDTO evaluateValue = createEvaluateValue(
                        evaluateResultItem.getValueId(), 
                        evaluateResultItem.getValueContent()
                    );
                    qualityItem.getUserValues().add(evaluateValue);
                }
            }
        }
    }
    
    /**
     * 填充质检值
     */
    private void populateQualityValues(List<QualityItemApiDTO> qualityItemList, 
                                      List<EvaluateResultItemApiDTO> qualityResultItemList) {
        if (Lists.isEmpty(qualityResultItemList)) {
            return;
        }
        
        for (QualityItemApiDTO qualityItem : qualityItemList) {
            for (EvaluateResultItemApiDTO qualityResultItem : qualityResultItemList) {
                if (Objects.equals(qualityItem.getAttrName(), qualityResultItem.getAttrName())) {
                    EvaluateValueApiDTO qualityValue = createEvaluateValue(
                        qualityResultItem.getValueId(), 
                        qualityResultItem.getValueContent()
                    );
                    qualityItem.getQualityValues().add(qualityValue);
                }
            }
        }
    }
    
    /**
     * 创建评估值对象
     */
    private EvaluateValueApiDTO createEvaluateValue(Long valueId, String valueContent) {
        EvaluateValueApiDTO evaluateValue = new EvaluateValueApiDTO();
        evaluateValue.setValueId(valueId);
        evaluateValue.setValueContent(valueContent);
        return evaluateValue;
    }
}
